package com.pilipili.serverapi.video.util;


import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.*;
/**
 * 处理m3u8文件里ts文件的请求路径
 *
 * @author chen.guosheng
 */
@Data
@Component
@PropertySource({"classpath:application.yml"})
public class M3u8FileHandler {

    @Value("${savePath.videoRequestPath}")
    private String videoRequestPath;

    @Value("${savePath.videoFilePath}")
    private String videoFilePath;

    public void handleM3u8File(String filePath){
//        String videoFilePath = "G:/pilipili/server-api/video/";
//        String videoRequestPath = "/pilipili/videoResource/";
        File file = new File(videoFilePath + filePath);
        String str[] = filePath.split("/");
        String fileDir = str[0];
        System.out.println(videoFilePath + filePath);
        System.out.println(file.exists());
        StringBuilder sb = new StringBuilder();
        if(file.exists()){
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                String lineStr;
                while((lineStr = reader.readLine()) != null){
                    if(!lineStr.contains(".ts")){
                        sb.append(lineStr + "\n");
                    }
                    else{
                        sb.append(videoRequestPath + fileDir + "/" + lineStr + "\n");
                    }
                }
                reader.close();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
                writer.write(sb.toString());
                writer.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
